package cn.school.web;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

/**
 * Servlet Filter implementation class RoleFilter
 */
@WebFilter("/*")
public class RoleFilter implements Filter {

	/**
	 * Default constructor.
	 */
	public RoleFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	// 怎么知道是否登录了...
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("开始权限的检查");
		HttpServletRequest req = (HttpServletRequest) request;
		String path = req.getServletPath();
		// 几个地址无条件放行
		if (path.equals("/adminlogin") || path.equals("/pages/userLogin.jsp")) {
			chain.doFilter(request, response);
			return;
		}
		if (req.getSession().getAttribute("USER_LOGIN") == null) {
			req.setAttribute("msg", "还没有登录,不能访问此页");
			req.getRequestDispatcher("/pages/userLogin.jsp").forward(request, response);
			return;
		}
		chain.doFilter(request, response);
		System.out.println("权限检查结束");
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
